package man.mungo.base.core.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Application extends ClassPathXmlApplicationContext implements
		BeanPostProcessor {

	private String[] propertiesLocations;

	public Application(String configLocation) {
		setConfigLocation(configLocation);
	}

	public Application(String[] configLocations) {
		setConfigLocations(configLocations);
	}

	public void start() {
		PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
		Resource[] resources = detectPropertiesFromConfigLocations(propertiesLocations);
		configurer.setLocations(resources);
		addBeanFactoryPostProcessor(configurer);
		refresh();
		super.start();
	}

	public void stop() {
		super.stop();
	}

	public Resource[] detectPropertiesFromConfigLocations(
			String[] propertiesLocations) {
		List<Resource> propertiesList = new ArrayList<Resource>();
		for (String propLocation : propertiesLocations) {
			Resource resource = new ClassPathResource(propLocation);
			if (resource.exists()) {
				try {
					resource.getInputStream();
					propertiesList.add(resource);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return propertiesList.toArray(new Resource[0]);
	}

	public String[] getPropertiesLocations() {
		return propertiesLocations;
	}

	public void setPropertiesLocations(String[] propertiesLocations) {
		this.propertiesLocations = propertiesLocations;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}
}
